﻿using System;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Windows.Forms.Design;

namespace PropertyGridEx
{

    /// <summary>   

    /// 在PropertyGrid 上显示日期控件    

    /// </summary>   

    public class UIDateTime : UITypeEditor
    {

        MonthCalendar dateControl = new MonthCalendar();
        IWindowsFormsEditorService edSvc = null;


        public UIDateTime()
        {
            dateControl.MaxSelectionCount = 1;
            this.dateControl.DateSelected += new System.Windows.Forms.DateRangeEventHandler(this.monthCalendar1_DateSelected);
  
        }

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {

            return UITypeEditorEditStyle.DropDown;

        }

        private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
        {
            //close 
            if (edSvc != null)
            {
                edSvc.CloseDropDown();
            }
        }

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context,System.IServiceProvider provider, object value)
        {

            try
            {
                edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (edSvc != null)
                {
                    if (value is string)
                    {
                        if ((string)value != "")
                        {
                            try
                            {
                                dateControl.SelectionStart = DateTime.Parse(value as String);
                            }
                            catch (Exception)
                            {
                                dateControl.SelectionStart = DateTime.Today;
                            }
                           
                        }
                        else
                        {
                            dateControl.SelectionStart = DateTime.Today;
                        }

                        edSvc.DropDownControl(dateControl);
                        

                        return dateControl.SelectionStart.ToShortDateString();
                        

                    }

                    else if (value is DateTime)
                    {

                        dateControl.SelectionStart = (DateTime)value;

                        edSvc.DropDownControl(dateControl);

                        return dateControl.SelectionStart;

                    }

                }

            }

            catch (Exception ex)
            {

                System.Console.WriteLine("PropertyGridDateItem Error : " + ex.Message);

                return value;

            }

            return value;

        }

    }

}
